package com.bjtg.threegoclinet.base;

import android.annotation.TargetApi;
import android.app.AlarmManager;
import android.app.Application;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.StrictMode;
import android.support.multidex.MultiDex;

import com.bjfl.saleManager.util.LogUtil;
import com.bjtg.threegoclinet.MainActivity;
import com.bjtg.threegoclinet.bean.GlobleMessage;
import com.bjtg.threegoclinet.okhttpUtils.OkHttpClientManager;
import com.bjtg.threegoclinet.util.LattePreference;
import com.log.LatteLogger;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.Logger;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.beta.interfaces.BetaPatchListener;
import com.tencent.bugly.beta.upgrade.UpgradeStateListener;

import java.util.Locale;

import cn.jpush.android.api.JPushInterface;

import static com.tencent.bugly.beta.tinker.TinkerManager.getApplication;

/**
 * Created by 86463 on 2017/11/18.
 */

public class MyApplication extends Application {

    public OkHttpClientManager mOkHttpClient;
    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplication();
        LogUtil.context = getApplication();

        Logger.addLogAdapter(new AndroidLogAdapter());
        JPushInterface.init(this);
        mOkHttpClient = new OkHttpClientManager();

        initHotFix();
    }

    private void initHotFix() {
        setStrictMode();

//        Beta.autoInit = true;

//        Beta.autoCheckUpgrade = true;

//        Beta.autoDownloadOnWifi = true;

//        Beta.upgradeCheckPeriod = 30 * 1000;

        /**
         * 只允许在MainActivity上显示更新弹窗，其他activity上不显示弹窗;
         * 不设置会默认所有activity都可以显示弹窗;
         */
        Beta.canShowUpgradeActs.add(MainActivity.class);
        /**
         * 设置启动延时为1s（默认延时3s），APP启动1s后初始化SDK，避免影响APP启动速度;
         */
        Beta.initDelay = 1 * 1000;
        // 设置是否开启热更新能力，默认为true
        Beta.enableHotfix = true;
        // 设置是否自动下载补丁
        Beta.canAutoDownloadPatch = false;
        // 设置是否提示用户重启
        Beta.canNotifyUserRestart = true;
        // 设置是否自动合成补丁
        Beta.canAutoPatch = true;


        /**
         *  全量升级状态回调
         */
        Beta.upgradeStateListener = new UpgradeStateListener() {
            @Override
            public void onUpgradeFailed(boolean b) {
                LatteLogger.e("Patch", "升级失败");
            }

            @Override
            public void onUpgradeSuccess(boolean b) {

                LatteLogger.e("Patch", "升级成功");
            }

            @Override
            public void onUpgradeNoVersion(boolean b) {
                LatteLogger.e("Patch", "最新版本_patch");
            }

            @Override
            public void onUpgrading(boolean b) {
                LatteLogger.e("Patch", "onUpgrading");
            }

            @Override
            public void onDownloadCompleted(boolean b) {
                LatteLogger.e("Patch", "补丁下载完成");
            }
        };

        /**
         * 补丁回调接口，可以监听补丁接收、下载、合成的回调
         */
        Beta.betaPatchListener = new BetaPatchListener() {
            @Override
            public void onPatchReceived(String patchFileUrl) {
                String patchUrl = patchFileUrl.substring(patchFileUrl.lastIndexOf("/") + 1,
                        patchFileUrl.lastIndexOf("."));
                if (!LattePreference.getPatchUrl(LattePreference.PATCH_URL).equals(patchUrl)) {
                    LattePreference.addPatchUrl(LattePreference.PATCH_URL, patchUrl);
                    Beta.downloadPatch();
                }
                LatteLogger.e("Patch", patchUrl);

            }

            @Override
            public void onDownloadReceived(long savedLength, long totalLength) {
                LatteLogger.d("Patch", String.format(Locale.getDefault(),
                        "%s %d%%",
                        Beta.strNotificationDownloading,
                        (int) (totalLength == 0 ? 0 : savedLength * 100 / totalLength)));
            }

            @Override
            public void onDownloadSuccess(String patchFilePath) {
            }

            @Override
            public void onDownloadFailure(String msg) {
                LatteLogger.e("Patch", "downloadFailure" + msg);
            }

            @Override
            public void onApplySuccess(String msg) {
                LatteLogger.e("Patch", "Success" + msg);
                LattePreference.addIsUpdate(LattePreference.IS_UPDATE, false);
                reboot();
            }

            @Override
            public void onApplyFailure(String msg) {
                LatteLogger.e("Patch", "Failure" + msg);
            }

            @Override
            public void onPatchRollback() {
                LatteLogger.e("Patch", "rollback");
            }
        };

        long start = System.currentTimeMillis();
        // 这里实现SDK初始化，appId替换成你的在Bugly平台申请的appId,调试时将第三个参数设置为true
        Bugly.init(this, "30e138eb73", GlobleMessage.isDebug);
        long end = System.currentTimeMillis();
        LatteLogger.e("init time--->", end - start + "ms");
    }

    private void reboot() {
        Intent mStartActivity = new Intent(this, MainActivity.class);
        int mPendingIntentId = 123456;
        PendingIntent mPendingIntent = PendingIntent.getActivity(this, mPendingIntentId, mStartActivity,
                PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager mgr = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
        System.exit(0);
    }


    @TargetApi(9)
    protected void setStrictMode() {
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitAll().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build());
    }

    public synchronized static Context getApplicationMyContext() {
        return context;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        // you must install multiDex whatever tinker is installed!
        MultiDex.install(base);
        // 安装tinker
        Beta.installTinker();
    }
}
